package cn.yangliu.nacos.comm.config.security.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yangliu.nacos.comm.enums.GlobalResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;


/**
 * The interface Security authentication entry point.
 *
 * @author 问道于盲
 */
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint, SecurityHandler {

    /**
     * Constructor
     */
    public SecurityAuthenticationEntryPoint() {
        super();
    }

    /**
     * Commences an authentication scheme.
     * <p>
     * <code>ExceptionTranslationFilter</code> will populate the
     * <code>HttpSession</code>
     * attribute named
     * <code>AbstractAuthenticationProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY</code>
     * with the requested target URL before calling this method.
     * <p>
     * Implementations should modify the headers on the
     * <code>ServletResponse</code> as
     * necessary to commence the authentication process.
     *
     * @param request       that resulted in an <code>AuthenticationException</code>
     * @param response      so that the user agent can begin authentication
     * @param authException that caused the invocation
     * @throws IOException      the io exception
     * @throws ServletException the servlet exception
     */
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {

        GlobalResultCode resultCode = GlobalResultCode.USER_IS_NOT_LOGIN;
        if (authException instanceof InsufficientAuthenticationException) {
            resultCode = GlobalResultCode.INSUFFICIENT_AUTHENTICATION;
        }

        handle(request, response, HttpStatus.UNAUTHORIZED, resultCode);

    }

}
